package com.cse.services.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.cse.mvc.models.Result;
import com.cse.services.SearchService;
import com.cse.services.SearchThread;
import com.cse.utils.AsyncCommunicationsInterface;
import com.mutear.ParallelSearcher.sort.RankSort;
import com.mutear.ParallelSearcher.utils.IResult;

/**
 * 搜索服务接口的实现类
 * @author Mutear
 *
 */
public class SearchServiceImpl implements SearchService, AsyncCommunicationsInterface {
	
	private List<IResult[]> results;
	
	public SearchServiceImpl() {
		results = new ArrayList<IResult[]>();
	}

	@Override
	public List<Result> search(String key, List<String> enginNmaes) {
		// 创建线程池
		ExecutorService pool = Executors.newFixedThreadPool(enginNmaes.size());
		for(int i = 0; i < enginNmaes.size(); i++){
			pool.execute(new SearchThread(this, enginNmaes.get(i), key));
		}
		try {
			pool.shutdownNow();
			pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
			// 对各组结果进行排序
			List<IResult> iResults = new RankSort(){
				@Override
				public IResult removeSimilar(IResult arg0, IResult arg1) {
					Result result0 = (Result) arg0;
					Result result1 = (Result) arg1;
					for(String name : result1.getEngineNames()){
						List<String> names = result0.getEngineNames();
						if(names.indexOf(name) < 0){
							names.add(name);
						}
					}
					result0.addUrl(result1.getUrl());
					return result0;
				}
			}
			.sort(results);
			List<Result> results = new ArrayList<Result>();
			for(IResult iResult : iResults){
				results.add((Result) iResult);
			}
			return results;
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void transferData(Object object) {
		results.add((IResult[])object);
	}

}
